/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cassandrawindow;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.crypto.Mac;

public class HandleDataTableBannerDate {
    
    public static final String KEYSPACE                             =   "AdsData";
    public static final String ColumFamly                           =   "BannerViewCountCf";
    public static final String ColumFamlyBannerClickCountCf         =   "BannerClickCountCf";
    public static final String ColumFamlyBannerViewCountCf          =   "BannerViewCountCf";

    public static final String ColumFamlyCampaignClickCountCf       =   "CampaignCountCf";
    public static final String ColumFamlyCampaignViewCountCf        =   "CampaignViewCountCf";
    
     public static final String ColumFamlyDateBanner_Geo_Counter    =   "DateBanner_Geo_Counter";
    
    public void handleData() throws ParseException, InterruptedException, ClassNotFoundException, InstantiationException, IllegalAccessException
    {
        //handle data by v3_cam_date
        Map<String,String> price_by_domain=new HashMap<>();
        List<Integer> listCampaigns = new ArrayList<Integer>();
        MysqlDataManager mysqlFaudClick = new MysqlDataManager();
        String currentDate = TimeUtil.getCurrentTimeInString();//2012-07-24
        //Debug.println("start time :" +TimeUtil.getCurrentTimeInStringForLog());
        //String currentDate = "2012-11-15";
        long first_time = System.currentTimeMillis();
        CassandraAction cassAct = new CassandraAction(ACCOUNT.CLUSTERNAME ,ACCOUNT.URL, ACCOUNT.PORT);
        cassAct.initReadWirte(KEYSPACE);
        
        MysqlDataManagerMain mysqldatamanager = new MysqlDataManagerMain();             
        listCampaigns = mysqldatamanager.getCampaignIdBySlice(currentDate);
        price_by_domain = mysqldatamanager.getPriceByDomain();
        //get all fraud click by date
        Map<String, Integer> fraudclicks = new HashMap<>();
        fraudclicks = mysqlFaudClick.getAllFraudClickByBannerid(currentDate);
        //get money by bannerid from domain table
        Map<String, Long> MoneyByBanner = new HashMap<>();
        MoneyByBanner = mysqlFaudClick.getMoneyByBannerId(currentDate);
        //max value
        Map<Integer, Long> MaxValue = new HashMap<>();
        MaxValue = mysqldatamanager.getMaxValueDaybyBannerId(currentDate);
        //get all bannerid stop
        List allBannerStopAndPause = new ArrayList();        
        allBannerStopAndPause = mysqldatamanager.getAllBanneridStoporPause(currentDate);
        //get number click by domain date
        Map<String, Long> ClickByDomainDate = new HashMap<>();
        ClickByDomainDate = mysqlFaudClick.getClickByDomainDate(currentDate);
        //get price by domain
        Map<String, Integer> PriceByDomain = new HashMap<>();
        PriceByDomain = mysqldatamanager.getPriceByDomain();
        
        StringBuilder sbff = new StringBuilder();
        Iterator it=listCampaigns.iterator();

        while(it.hasNext())
        {            
            String camid    =   (String)it.next();
            List bannerids  =   mysqldatamanager.getBannerIDByCampaignId(Integer.valueOf(camid),currentDate);
            Iterator it1    =   bannerids.iterator();

            while(it1.hasNext())
            {
                String bannerid = (String)it1.next();
                String str = getDataCampaignAndBannerID(cassAct, currentDate, camid, bannerid,ColumFamlyBannerClickCountCf, ColumFamlyBannerViewCountCf,ColumFamlyDateBanner_Geo_Counter,fraudclicks,MoneyByBanner,MaxValue,allBannerStopAndPause,ClickByDomainDate,PriceByDomain);
                sbff.append(str);
            }

            if(sbff.toString().length() > 1000)
            {
                MysqlDataManager mysql = new MysqlDataManager();
                //xu li cho du lieu cuoi
                String relStr = sbff.toString();
                String valInsert = relStr.substring(0, (relStr.length()-1));
                mysql.insertSliceDataCampaignAndBanner(valInsert);
                sbff.setLength(0);
            }
        }
        //xu li cho du lieu cuoi
        if(sbff.toString().length() > 1)
        {
            MysqlDataManager mysql = new MysqlDataManager();        
            String relStr = sbff.toString();
            String valInsert = relStr.substring(0, (relStr.length()-1));
            mysql.insertSliceDataCampaignAndBanner(valInsert);
            sbff.setLength(0);
        }
        
        long last_time = System.currentTimeMillis();
        Debug.println("Thoi gian chay  :" +(last_time-first_time));
        Debug.println("success HandleDataTableBannerDate");

    }
    public static void removeDuplicateWithOrder(ArrayList arlList)
    {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = arlList.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (set.add(element))
            newList.add(element);
        }
        arlList.clear();
        arlList.addAll(newList);
    }
    public static String getDataCampaignAndBannerID(CassandraAction cassAct,String currentDay,String camId,String banId,String columnFamilyClick,String columnFamilyView,String ColumFamlyDateBanner_Geo_Counter,Map<String, Integer> fraudclicks,Map<String, Long> MoneyByBanner,Map<Integer, Long> MaxValue,List allBannerStopAndPause,Map<String, Long> ClickByDomainDate,Map<String, Integer> PriceByDomain) throws ParseException
    {
        StringBuilder sb = new StringBuilder();
        List clickanddomain = new ArrayList();
        /*
        long start_time = TimeUtil.getCurrentTime()*1000 - 1*60*60*1000;// cách thời điểm hienj tại một 1h        
        long finish_time = start_time + 30*60*1000; //cach thời điểm hiện tại 30 phút
        */
        String changeDay = currentDay.split("-")[2]+ "/" + currentDay.split("-")[1]+"/" + currentDay.split("-")[0];               
        String date = "00:00:00 " + changeDay ;
        long start_time = TimeUtil.longToDateWithHour(date);
        //them 1 ngay
        long finish_time = start_time + 24*60*60*1000;
        long countClick = cassAct.getCountClickByIntervalTime(banId, columnFamilyClick, start_time, finish_time);
        long countView = cassAct.getCountClickByIntervalTime(banId, columnFamilyView, start_time, finish_time);       
        
        //if view >0
        if((countView >0))
        {   //if have fraudClick
            if(fraudclicks.containsKey(Integer.valueOf(banId)+"_"+currentDay))
            {
                long fraud_click = fraudclicks.get(Integer.valueOf(banId)+"_"+currentDay);
                //if have Money by Bannerid
                if(MoneyByBanner.containsKey(banId))
                {
                    //check xem banner da stop hay pause chua
                    //if stop hoac pause thi khong tinh tien nua
                    //neu vuot qua ngan sach thi lay them 20% ngan sach
                    //neu khong vuot thi van tinh tien binh thuong
                    if(allBannerStopAndPause.contains(Integer.valueOf(banId)))
                    {                        
                        long maxValueDay = MaxValue.get(Integer.valueOf(banId));                        
                        long moneyByBannerid = MoneyByBanner.get(banId);
                        //if vuot qua 1.2 lan ngan sach thi tinh them 20%
                        //clickcharge lay tu realclick - so click phan du so voi 120% ngan sach tu bang domaindate
                        //so tien se la 120% ngan sach
                        if(moneyByBannerid >= 1.2*maxValueDay)
                        {
                            //so du se dung de tinh clickcharge
                            long diffMoney = (long) (moneyByBannerid - 1.2 * maxValueDay);
                            //tinh toan clickcharge
                            int clickCharge = getClickChargeByBannerid(diffMoney, currentDay, Integer.valueOf(banId), ClickByDomainDate, PriceByDomain);
                            
                            String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click) +","+(countClick-fraud_click-clickCharge) +"," + String.valueOf(countView) +",0,0,0,0,0,0,0,'" + currentDay + "'," + 1.2*maxValueDay +")";
                            //String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click) +",0," + String.valueOf(countView) +",0,'" + currentDay + "',0)";
                            sb.append(insertData).append(",");
                        }
                        //if khong vuot tinh binh thuong
                        //khi do clickcharge = realclick
                        //so tien se lay tu bang domain date
                        else{                            
                            String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click) +"," + (countClick-fraud_click) +","+ String.valueOf(countView) +",0,0,0,0,0,0,0,'" + currentDay + "'," + moneyByBannerid+")";
                            //String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click) +",0," + String.valueOf(countView) +",0,'" + currentDay + "',0)";
                            sb.append(insertData).append(",");
                        }
                    }
                    //if continue
                    else {
                        long maxValueDay = MaxValue.get(Integer.valueOf(banId));
                        long moneyByBannerid = MoneyByBanner.get(banId);
                        //long moneyByBannerid = 30000000;
                        if(moneyByBannerid >= 1.2*maxValueDay)
                        {
                            //so du se dung de tinh clickcharge
                            long diffMoney = (long) (moneyByBannerid - 1.2 * maxValueDay);
                            //tinh toan clickcharge
                            int clickCharge = getClickChargeByBannerid(diffMoney, currentDay, Integer.valueOf(banId), ClickByDomainDate, PriceByDomain);
                            String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click)+"," + (countClick-fraud_click-clickCharge) +"," + String.valueOf(countView) +",0,0,0,0,0,0,0,'" + currentDay + "'," + 1.2*maxValueDay +")";
                            //String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click) +",0," + String.valueOf(countView) +",0,'" + currentDay + "',0)";
                            sb.append(insertData).append(",");
                        }
                        //if khong vuot tinh binh thuong
                        //khi do clickcharge = realclick
                        //so tien se la so tien tu bang domain date
                        else{
                            String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click) +"," + (countClick-fraud_click) +","+ String.valueOf(countView) +",0,0,0,0,0,0,0,'" + currentDay + "'," + moneyByBannerid+")";
                            //String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click) +",0," + String.valueOf(countView) +",0,'" + currentDay + "',0)";
                            sb.append(insertData).append(",");
                        }
                    }
                } else {
                    String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click) +",0," + String.valueOf(countView) +",0,0,0,0,0,0,0,'" + currentDay + "',0)";
                    //String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click) +",0," + String.valueOf(countView) +",0,'" + currentDay + "',0)";
                    sb.append(insertData).append(",");                    
                }
            } else{               
                if(MoneyByBanner.containsKey(banId))
                {
                    long moneyByBannerid = MoneyByBanner.get(banId);
                    String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick)+","+countClick+ ","+ String.valueOf(countView) +",0,0,0,0,0,0,0,'" + currentDay + "',"+moneyByBannerid+")";
                    sb.append(insertData).append(",");
                } else {                    
                    String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick)+"," +countClick+ ","+ String.valueOf(countView) +",0,0,0,0,0,0,0,'" + currentDay + "',0)";
                    sb.append(insertData).append(",");
                }
            }            
        }
        //mysqldatamanager.insertDataCampaignAndBanner(String.valueOf(camId),String.valueOf(banId), String.valueOf(countClick), String.valueOf(countView), (prefixDB +i));
        return sb.toString();
    }

    public static int getClickChargeByBannerid(long totalMoney,String currentDay,int bannerid,Map<String, Long> ClickByDomainDate,Map<String, Integer> PriceByDomain)
    {
        Map<String, Long> DomainAndClick = new HashMap<>();
        int retValue    = 0;
        int totalClick  = 0;
        //lay cac domain tinh tien ra
        Set s = PriceByDomain.entrySet();        
        Iterator it=s.iterator();
        //tim so click ung voi moi domain va bannerid
        while(it.hasNext())
        {            
            Map.Entry m =(Map.Entry)it.next();
            //key là domain
            String key=(String)m.getKey();
            
            if(ClickByDomainDate.containsKey(String.valueOf(bannerid)+"_"+key+"_"+currentDay))
            {
                long numberClick = ClickByDomainDate.get(String.valueOf(bannerid)+"_"+key+"_"+currentDay);
                totalClick += numberClick;
                DomainAndClick.put(key, numberClick);
            }
        }
        //lay tung phan tu ra roi tinh clickcharge
        Set s1 = DomainAndClick.entrySet();
        Iterator it1=s1.iterator();
        while(it1.hasNext())
        {
            Map.Entry m =(Map.Entry)it1.next();
            //key là domain
            String  key=(String)m.getKey();
            //gia tri la tong click theo domain ung voi bannerid
            long    value     =   (Long)m.getValue();
            int     temp1     =   (int)(value/(totalClick));
            //lay gia moi domain
            int price = (int)PriceByDomain.get(key);
            //tinh tổng clickcharge
            retValue =+ (int) (temp1 * totalMoney/price);
        }
        return retValue;
    }
}
